-- item_num_gen.lua
-- Scans an adjacent inventory and interactively helps create/update a crafting request file.
-- Version with robust manual file writing to avoid serialization issues.

local sides = require("sides")
local component = require("component")
local fs = require("filesystem")
-- 'serialization' is no longer required due to manual file writing.

local ic = component.inventory_controller
if not ic then
  print("Error: Component 'inventory_controller' not found.")
  print("Please ensure an Inventory Controller is connected to the computer.")
  return
end

local CONFIG_PATH = "/home/item_num.txt"
local items_to_craft = {}
local new_items_found = false

local function get_item_key(stack)
  if not stack or not stack.name then return nil end
  return stack.name .. ":" .. tostring(stack.damage or 0)
end

-- 1. 加载现有配置
if fs.exists(CONFIG_PATH) then
  print("Existing config file found. Scanning for new items to add...")
  local f, err = loadfile(CONFIG_PATH)
  if f then
    items_to_craft = f()
    if type(items_to_craft) ~= "table" then
      print("Warning: Config file appears corrupted. A new one will be created.")
      items_to_craft = {}
    end
  else
    print("Warning: Could not load config file, creating a new one. Error: " .. tostring(err))
    items_to_craft = {}
  end
else
  print("No config file found. Scanning inventory to create a new file...")
end

-- 创建一个快速查找表，用于判断物品是否已存在于配置中
local existing_keys = {}
for _, entry in ipairs(items_to_craft) do
  if entry.item then
    existing_keys[get_item_key(entry.item)] = true
  end
end

-- 2. 扫描物品栏并处理新物品
print("Scanning inventory on side: up")
local inventory_size = ic.getInventorySize(sides.up)
if not inventory_size or inventory_size == 0 then
    print("Error or empty inventory on the 'up' side. Aborting.")
    return
end

for i = 1, inventory_size do
  local stack = ic.getStackInSlot(sides.up, i)
  if stack then
    local key = get_item_key(stack)
    
    -- 结合了新物品检测和交互式输入的逻辑
    if key and not existing_keys[key] then
      new_items_found = true
      
      print("\n----------------------------------------")
      print("  >> New Item Detected! <<")
      print("  Label:  " .. stack.label)
      print("  Name:   " .. stack.name)
      print("  Damage: " .. tostring(stack.damage or 0))
      print("----------------------------------------")
      
      local quantity = nil
      while true do
        io.write("Enter desired quantity for this item (number >= 0): ")
        local input = io.read()
        quantity = tonumber(input)
        
        if quantity and quantity >= 0 and math.floor(quantity) == quantity then
          break
        else
          print("Invalid input. Please enter a whole number like 0, 64, or 1000.")
        end
      end
      
      table.insert(items_to_craft, {
        item = {name = stack.name, damage = stack.damage or 0, label = stack.label},
        quantity = quantity
      })
      existing_keys[key] = true
      
      if quantity > 0 then
        print("--> Added '" .. stack.label .. "' with a target of " .. quantity .. ".\n")
      else
        print("--> Added '" .. stack.label .. "' to the list, but with target quantity 0.\n")
      end
    end
  end
end

-- 3. 将最终结果写回文件
if not new_items_found then
  print("\nNo new items found in the inventory. Configuration file is unchanged.")
  return
end

-- ######################################################################
-- ## 使用你提供的、经过修复的、健壮的手动文件写入逻辑
-- ######################################################################
print("\nAll new items processed. Writing updated configuration...")

local file, err = io.open(CONFIG_PATH, "w")
if not file then
  print("FATAL ERROR: Could not open config file for writing: " .. tostring(err))
  return
end

-- 写入文件头
file:write("return {\n")

-- 循环遍历所有物品（包括旧的和新添加的）并格式化输出
for i, entry in ipairs(items_to_craft) do
  local item = entry.item
  local quantity = entry.quantity
  
  -- 使用 string.format 和 %q 来安全地处理包含特殊字符的字符串
  local item_line = string.format(
    "  {item={name=%q, damage=%d, label=%q}, quantity=%d}",
    item.name,
    item.damage or 0,
    item.label or item.name, -- 如果物品没有标签，则使用其内部名称作为备用
    quantity
  )
  
  file:write(item_line)
  
  -- 在除最后一行外的每一行末尾添加一个逗号
  if i < #items_to_craft then
    file:write(",\n")
  else
    file:write("\n")
  end
end

-- 写入文件尾
file:write("}\n")
file:close()
-- ######################################################################

print("Successfully wrote " .. #items_to_craft .. " unique item entries to " .. CONFIG_PATH)
